package com.hardydou.pattern.singleton;

import java.util.concurrent.atomic.AtomicInteger;


/**
 * 单例模式
 * <p>
 * 双重检查锁定模式
 * <p>
 * 注意：
 * <p>
 * DoubleCheck 不被提倡使用，理由：java的内存模型（jmm）导致会出现无序写入会导致失效。
 * <p>
 * 作者在Jdk1.8下面 测试数次均为发现问题，但也未曾求证 无序写入问题是否被解决。
 *
 * @author hardy
 */
public class DoubleCheckSingleton {

    private static AtomicInteger count = new AtomicInteger(0);

    public static volatile DoubleCheckSingleton instance;
    private static boolean initOk = false;


    private DoubleCheckSingleton() {
        count.getAndIncrement();
        try {
            Thread.sleep(500L);
        } catch (Exception e) {

        }
        initOk = true;

    }

    public static DoubleCheckSingleton getInstance() {
        if (instance == null) {
            synchronized (DoubleCheckSingleton.class) {
                if (instance == null) {
                    instance = new DoubleCheckSingleton();
                }
            }

        }

        return instance;
    }

    public static int getCount() {
        return count.get();
    }



    public static boolean hasInit() {
        return initOk;
    }
}
